//
//  ST_LaunchChargeWidget.swift
//  btvideo
//
//  Created by mac on 2021/4/29.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SwiftyUserDefaults

class ST_LaunchChargeWidget: NSObject {
    
    //MARK: - Share Instance
    static let shared = ST_LaunchChargeWidget()
    
    private override init() {
        super.init()
        
        binding()
    }
    
    
    private func binding(){
        
        layout_charge_behavior.subscribe(onNext: { layoutRootView in
            
            if let v = layoutRootView,v != self.root_view.superview{
                
                v.addSubview(self.root_view)
                self.root_view.snp.makeConstraints { (make) in
                    make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-109)
                    make.height.width.equalTo(73)
                    make.left.equalToSuperview()
                }
                
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.fetch_boot_data()
            }else{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    
    ///布局
    var layout_charge_behavior = BehaviorRelay<UIView?>(value: nil)
    
    fileprivate lazy var root_view:UIControl = {
        let control = UIControl()
        control.alpha = 0
        control.isHidden = true
        control.addTarget(self, action: #selector(push_first_charge), for: UIControl.Event.touchUpInside)
        
        control.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        
        control.addSubview(count_down_label)
        count_down_label.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-3)
        }
        
        control.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(count_down_label.snp.top).offset(0)
        }
        
        return control
    }()
    
    fileprivate lazy var imageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("firstCharge"))
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "首充送豪礼"
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var count_down_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 9, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate weak var handle_controller:ST_FirstChargeController?
    
    fileprivate var count_down_seconds = 0
    
    fileprivate var timer:Timer?
    
    fileprivate(set) var productId:String?
    
    /// 买过首冲
    fileprivate(set) var first_recharge_paid:Bool?
}

extension ST_LaunchChargeWidget{
    
    fileprivate func stop_charge_action(){
        
        timer?.invalidate()
        
        timer = nil
        
        root_view.isHidden = true
        
        handle_controller?.timer_handle(str: nil)
    }
    
    @objc fileprivate func startTimer(){
        
        timer?.invalidate()
        
        timer = nil
        
        handle_controller?.timer_handle(str: nil)
        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timer_handle), userInfo: nil, repeats: true)
        
        timer_handle()
    }
    
    @objc fileprivate func timer_handle(){
        
        if count_down_seconds == 0{
            
            stop_charge_action()
            
            return
        }
        
        count_down_seconds -= 1
        
        count_down_label.text = seconds_to_hours_minutes_seconds_string(seconds: count_down_seconds)
        
        root_view.isHidden = false
        
        handle_controller?.timer_handle(str: count_down_label.text)
        
    }
    
    
    @objc  func push_first_charge(){
        
        let vc = ST_FirstChargeController()
        
        vc.overCurrentContext = true
        
        vc.productId = self.productId
        
        handle_controller = vc
        
        GlobalPresent(toController: vc)
        
    }
    
}


extension ST_LaunchChargeWidget{
    
    func fetch_boot_data() {
        
        if let user = ST_BTUserInfoManager.shared.current_account_info?.userinfo,user.sex == .female{
            return
        }
        
        TIANSession(requestUrl: PH.firstChargeApi).wrap_response_data().retry(maxAttempts: 10, delay: 1).subscribe(onNext: { json in
            
            print("首冲返回json:",json)
            
            self.count_down_seconds = json["data"]["count_down"].intValue
            
            let id = json["data"]["id"].stringValue
            if id.count > 0 {
                self.productId = id
            }else{
                self.productId = nil
            }
            
            self.first_recharge_paid = json["data"]["is_paid"].boolValue
            
            /// 未支付 并且有倒计时 展示UI
            if self.count_down_seconds > 0 && self.first_recharge_paid == false{
                self.startTimer()
            }else{
                self.stop_charge_action()
            }
            
        }).disposed(by: rx.disposeBag)
        
        
    }
    
    func clear_data() {
        
        self.productId = nil
        self.first_recharge_paid = nil
        
        self.stop_charge_action()
    }
    
    func change_widget_state(tabControlTag:Int)  {
        
        self.root_view.alpha = tabControlTag < 3 ? 1 : 0
        
    }
    
    
}
